(function() {
  'use strict';

  angular.module('DeployTool')
    .directive('confirmPopup', ['$timeout', ConfirmPopupDirective])
    .directive('messageTips', ['$timeout', '$rootScope', MessageTipsDirective]);

  function ConfirmPopupDirective($timeout) {
    var directive = {
      restrict: 'A',
      scope: {
        confirmPopup: '&',
        confirmTitle: '=',
        confirmContent: '=',
        enabled: '@?',
      },
      link: link,
      transclude: true,
      template: '<div class="trans-clude" ng-transclude ng-click="show()"></div>' +
        '<div class="modal fade confirm-modal">' +
        '<div class="modal-dialog">' +
        '<div class="modal-content">' +
        '<div class="modal-header">' +
        '<span class="close iconfont icon-close" ng-click="close()"></span>' +
        '<h4 class="modal-title" ng-bind="confirmTitle"></h4>' +
        '</div>' +
        '<div class="modal-body">' +
        '<p class="text-center" ng-bind="confirmContent"></p>' +
        '</div>' +
        '<div class="modal-footer">' +
        '<button class="button-cancel" ng-click="close()">取消</button>' +
        '<button class="button-confirm" ng-click="confirm()">确定</button>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>'
    };

    return directive;

    function link(scope, element, attrs) {

      scope.show = function() {
        if (scope.enabled === 'false') {
          return;
        }
        element.find('.modal').modal();
      };

      scope.close = function() {
        element.find('.modal').modal('hide');
      };

      scope.confirm = function() {
        element.find('.modal').modal('hide');
        $timeout(function() {
          scope.confirmPopup();
        }, 500);
      };
    }
  }

  function MessageTipsDirective($timeout, $rootScope) {

    var directive = {
      restrict: 'EA',
      link: link,
      replace: true,
      template: '<div class="message-tips"></div>'
    };

    return directive;

    function link(scope, element, attrs) {

      //level: success,info,warning,danger
      $rootScope.showMessage = function(message, level, delay) {
        var tip = angular.element('<div class="alert message-tip"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button>' + message + '</div>').appendTo(element);
        tip.addClass('alert-' + level);

        if (delay) {
          $timeout(function() {
            tip.alert('close');
          }, delay * 1000);
        }
      };
    }
  }

  angular.element('body').append('<div message-tips></div>');
})();